package com.cfl.shiro;

import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class MyRealm extends AuthorizingRealm{

	/**
	 * 为当前登录的用户授予角色和权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		
		try {
			Set<String> roleSet = new HashSet<String>();		// 角色
			Set<String> permissionSet = new HashSet<String>();	// 权限
			String username = (String) principals.getPrimaryPrincipal();
			String sql = " select t_role.role_name, t_permission.permission_name from t_role"
					   + " left join t_role_permission"
					   + " on t_role.id = t_role_permission.roleId "
					   + " left join t_permission "
					   + " on t_role_permission.permissionId = t_permission.id "
					   + " left join t_user "
					   + " on t_user.roleId = t_role.id "
					   + " where t_user.username = '"+username+"'";
			System.out.println("sql: " + sql);
			ResultSet resultSet = JDBCUtil.executeQuery(sql);
			if(resultSet != null)
			{
				while (resultSet.next()) {
					roleSet.add(resultSet.getString("role_name"));
					permissionSet.add(resultSet.getString("permission_name"));
					System.out.println("role_name: " + resultSet.getString("role_name") + "permission_name: " + resultSet.getString("permission_name"));
				}
			}
			SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
			simpleAuthorizationInfo.setStringPermissions(permissionSet);
			simpleAuthorizationInfo.setRoles(roleSet);
			return simpleAuthorizationInfo;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/**
	 * 验证当前登录的用户
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		try {
			String username = (String) token.getPrincipal();
			String password = "";
			ResultSet resultSet = JDBCUtil.executeQuery("select * from t_user where username = '"+username+"'");
			if(resultSet != null)
			{
				while (resultSet.next()) {
					password = resultSet.getString("password");
				}
				AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, "");
				return authenticationInfo;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
